package com.pavlinic.mylisp.repl;

import java.io.IOException;
import java.util.List;

import com.pavlinic.mylisp.Expression;
import com.pavlinic.mylisp.GlobalEvaluationContext;
import com.pavlinic.mylisp.parser.Parser;
import com.pavlinic.mylisp.parser.Tokenizer;
import com.pavlinic.mylisp.util.IOUtils;

public class Bootstrapper {
	private static Bootstrapper instance;
	private static final Parser PARSER = new Parser(new Tokenizer());
	
	private Bootstrapper() {
	}
	
	public void bootstrap() {
		loadFromClasspathInternal("arithmetic.lisp");
		loadFromClasspathInternal("system.lisp");
		loadFromClasspathInternal("conversions.lisp");
		loadFromClasspathInternal("lists.lisp");
		loadFromClasspathInternal("equality.lisp");
	}

	private void loadFromClasspathInternal(String file) {
		try {
			final String contents = IOUtils.readAll(getClass().getClassLoader().getResourceAsStream(file));
			final List<Expression> expressions = PARSER.parseMultipleExpressions(contents);
			for (Expression expression : expressions) {
				expression.evaluate(GlobalEvaluationContext.getInstance());
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static Bootstrapper getInstance() {
		if (instance == null) {
			instance = new Bootstrapper();
		}
		return instance;
	}
	
	public static void loadFromClasspath(String file) {
		getInstance().loadFromClasspathInternal(file);
	}
}
